var overview = function ($) {
    var self = {};
    var charts = {
        "concurrent_users": ["total"],
        "view_event": ["total"],
        "leave_event": ["total"],
        "comment": ["total"],
        "like": ["total"],
        "engagement": ["total"],
        "follow": ["total"],
        "share": ["total"]
    }

    var connect = function (url) {
        var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
        return new WS(url);
    }

    var createCharts = function (metrics) {
        for (var metric in metrics) {
            var $el = $("#" + metric)

            if ($el.length > 0) {
                metrics[metric].chart = Chart.create($el)
            }
        }
    }

    var requestMetrics = function (connection, context, contextId, resolution, metrics) {
        connection.send(JSON.stringify({
            context: context,
            contextId: new String(contextId),
            resolution: resolution,
            metrics: metrics
        }))
    }

    var convertTimeSeries = function (metric) {
        var timeSeries = []

        var i = metric.slices.length
        while (i--) {
            var data = []
            var z = metric.slices[i].data.length;

            while (z--) {
                var dataPoint =  metric.slices[i].data[z]
                data[z] = [dataPoint.ts, dataPoint.value]
            }

            var series = {
                name: metric.slices[i].label,
                data: data
            }
            timeSeries.push(series)
        }
        return timeSeries
    }

    var renderFullChart = function (metrics) {
        var i = metrics.length

        while (i--) {
            var metric = metrics[i]
            var $el = $("#" + metric.name);

            if ($el.length > 0) {
                charts[metric.name].chart = Chart.render($el, convertTimeSeries(metric), metric.unit)
            }
        }
    }

    var findChartSeries = function (name, label) {
        var chart = charts[name].chart.highcharts()

        for (var i = 0; i < chart.series.length; i++) {
            if (chart.series[i].name == label) {
                return chart.series[i]
            }
        }
    }

    var updateChart = function (metrics) {
        var i = metrics.length
        while (i--) {
            var metric = metrics[i]
            var timeSeries = convertTimeSeries(metric)

            var j = timeSeries.length
            while (j--) {
                var series = findChartSeries(metric.name, timeSeries[j].name)

                if (series) {
                    for (var z = 0; z < timeSeries[j].data.length; z++) {
                        var point = [timeSeries[j].data[z][0], timeSeries[j].data[z][1]]
                        console.log("Updating metric " + metric.name +  " series " + timeSeries[j].name
                            + " point: " + point[0] + " -> " + point[1])
                        series.addPoint(point, true, true)
                    }
                }
            }
            console.log(metric)
        }
    }

    var processMetrics = function (msg) {
        var message = jQuery.parseJSON(msg.data)

        if (message.responseType == "full") {
            renderFullChart(message.metrics)
        } else {
            updateChart(message.metrics)
        }
    }

    self.start = function (url) {
        var $dashboard = $('#dashboard');
        var context = $dashboard.data('context');
        var contextId = $dashboard.data('context-id');
        var resolution = $dashboard.data('metric-resolution');

        createCharts(charts)
        var connection = connect(url)

        connection.onopen = function () {
            requestMetrics(connection, context, contextId, resolution, charts);
        }

        connection.onmessage = function (msg) {
            processMetrics(msg)
        }
    }

    return self;
}(jQuery);

